module.exports = (config, ddd) => {
  var express = require("express");
  var router = express.Router();
  router.get("/", (req, res) => {
    ddd.list().then((d) => {
      res.json(d);
    });
  });

  router.all("/:sp", async function (req, res, next) {
    console.log({
      "req cookies:": JSON.stringify(req.cookies),
      sp: req.params.sp,
      method: req.method,
      body: req.body,
      query: req.query,
      header: req.header,
    });
    let data;
    switch (req.method) {
      case "GET":
        data = req.query ?? {};
        break;
      case "POST":
        data = req.body ?? {};
        break;
      default:
        break;
    }

    // ddd.exec({
    //   sp: "ddd_log_submit",
    //   token: req.cookies[config.tokencookie],
    //   data: { sp: req.params.sp, result: {}, jdata: data },
    // });

    ddd
      .exec({
        sp: "ddd_" + req.params.sp,
        token: req.cookies[config.tokencookie],
        data: data,
      })
      .then((result) => {
        if (req.method === "GET") {
          res.header("Cache-control", "max-age=60");
        }
        res.type("application/json");
        res.json(result);
      })
      .catch((err) => {
        console.log({ err });
        if (err?.code === "ER_SP_DOES_NOT_EXIST") {
          next();
        } else {
          res.status(500);
          res.send(err);
        }
      });
  });
  return router;
};
